import { Injectable }     from '@angular/core';
import { CanActivate, CanActivateChild }    from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Service } from "../main/app.service";
import { SessionStorage } from "./session.storage";
import utils from 'app/tools/config';
declare const  LoginAddress: string;

@Injectable()
export class AuthGuard implements CanActivate,  CanActivateChild {
    constructor(public service: Service, public storage: SessionStorage){}
    canActivate(): Observable<boolean> {
        const localParam = this.stringToJson(location.href);
        if(!localParam){
            this.storage.clear();
            location.href =  LoginAddress;
        }
        return new Observable(observer=>{
            this.service.checkToken()
            .map(res=>{
                console.log(res);
                return res;
            })
            .map(result=>result["result"]==="success")
            .subscribe(bool=>{
                if(bool){
                    observer.next(bool);
                    observer.complete();
                }else{
                    console.error("权限认证失败");
                    this.storage.clear();
                    location.href =  LoginAddress;
                    observer.next(bool);
                    observer.complete();                
                }
                
            },err=>{
                console.error("权限认证失败");
                this.storage.clear();
                location.href =  LoginAddress;
                observer.next(false);
                observer.complete();  
            })
        })
  }
  canActivateChild(): Observable<boolean> {
    console.log("是否进入该子路由........");
    const localParam = this.stringToJson(location.href);
    if(!localParam){
        this.storage.clear();
        location.href =  LoginAddress;
    }
    return this.canActivate();
  }


  stringToJson(str: string): Object|Boolean{
    if(utils.ipMap['getMsgFromUrl']){
        if(this.storage.getJson("token")){
            return true;
        }else{
            let needArr = {};
            if(str.includes("?")&&str.includes("tokenId")){
                str = str.split("?")[1];
                let arr = str.split("&");
                arr.map((x,y,z)=>{
                    needArr[x.split("=")[0]] = x.split("=")[1]
                });
                this.storage.setJson("token",needArr);
                return needArr;
            }else if(this.storage.getJson("token")){
                needArr = this.storage.getJson("token");
                return needArr;
            }else{
                return false;
            }
        }
    }else{
        if(this.storage.getJson("token")){
            return true;
        }else{
            return false;
        }
    }
    
    
}
}